package dbunit.export

import java.sql.Connection
import org.apache.log4j.Logger
import org.dbunit.database.DatabaseConnection
import org.dbunit.database.IDatabaseConnection
import org.dbunit.database.QueryDataSet
import org.dbunit.dataset.IDataSet
import org.dbunit.dataset.xml.XmlDataSet

/**
 * Created by IntelliJ IDEA.
 * User: pradeep
 * Date: 12/21/10
 * Time: 4:48 PM
 * to export database into file
 */
class DataSetExport {

     Logger gLogger = Logger.getLogger(DataSetExport.class);

     private static  DataSetExport instance = null

    /**
     * returns the instance
     * @return
     */
     public static  DataSetExport getInstance() {
       if (instance == null) {
         instance = new  DataSetExport()
       }

       return instance
     }

    /**
     * Export the full database in XML file
     *
     * @param jdbcConnection
     * @param fileName
     * @throws Exception
     */
    public void exportFullDataBase(Connection jdbcConnection, String fileName) throws Exception {

        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);

        gLogger.info("connection :: "+connection);
        // full database export
        IDataSet fullDataSet = connection.createDataSet();
        gLogger.info("fullDataSet :: "+fullDataSet);

        XmlDataSet.write(fullDataSet, new FileOutputStream(fileName + ".xml"));
    }

    /**
     * Export the data for a particular table
     *
     * @param jdbcConnection
     * @param tableName
     * @param fileName
     * @throws Exception
     */
    public void exportPartialDataSet(Connection jdbcConnection, Set<String> tableName, String fileName) throws Exception {
        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);

        // partial database export
        QueryDataSet partialDataSet = new QueryDataSet(connection);

        for (String s : tableName) {
            partialDataSet.addTable(s);
        }

        XmlDataSet.write(partialDataSet, new FileOutputStream(fileName + ".xml"));
    }
}
